package com.jean.business.admin;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;

import com.jean.business.bean.AdminInfo;
import com.jean.common.ConstantConfigs;
import com.jean.util.LoggerFactory;

public class AdminSessionManage
{
    /**
     * 日志
     */
    private static Logger logger = LoggerFactory.getLogger();
    
    /**
     * <一句话功能简述>刷新session
     * <功能详细描述>
     * @param request 请求
     * @see [类、类#方法、类#成员]
     */
    public static void refreshSession(HttpServletRequest request)
    {
        if (request == null)
        {
            logger.warn("the HttpServletRequest is null.");
            return;
        }
        if (request.getSession() == null)
        {
            logger.warn("the HttpSession is null.");
            request.getSession(true);
            return;
        }
        // 遍历session内容，存入Map
        Map<String, Object> sessionMap = new HashMap<>();
        Enumeration<String> enums = request.getSession().getAttributeNames();
        while (enums.hasMoreElements())
        {
            String sessionName = (String)enums.nextElement();
            sessionMap.put(sessionName,
                request.getSession().getAttribute(sessionName));
        }
        request.getSession().invalidate();
        request.getSession(true);
        Iterator iterator = sessionMap.entrySet().iterator();
        while (iterator.hasNext())
        {
            Map.Entry entry = (Map.Entry)iterator.next();
            if("JSESSIONID".equals(entry.getKey()))
            {
                continue;
            }
            logger.info("session attrbutes: " + entry.getKey());
            request.getSession().setAttribute((String)entry.getKey(), entry.getValue());
        }
    }
    
    /**
     * <一句话功能简述>管理员是否在线
     * <功能详细描述>
     * @param request
     * @return
     * @see [类、类#方法、类#成员]
     */
    public static boolean isAdminOnline(HttpServletRequest request)
    {
        if (request == null)
        {
            logger.warn("the HttpServletRequest is null.");
            return false;
        }
        if (request.getSession() == null)
        {
            logger.warn("the HttpSession is null.");
            return false;
        }
        AdminInfo adminInfo = (AdminInfo)request.getSession().getAttribute(ConstantConfigs.SESSION_ADMIN_ACCOUNT);
        if(adminInfo == null || StringUtils.isEmpty(adminInfo.getAccount()))
        {
            logger.warn("the admininfo in session is null.");
            return false;
        }
        return true;
    }
}
